import './ActivityEditor.less'
import { useEffect, useState, useRef } from 'react'
import { useModel, useSearchParams } from '@umijs/max'
import { Button, Collapse, Popconfirm, Tooltip, App, Spin } from 'antd'
import CouponCom from './components/CouponCom/CouponCom'
import PageSettingCom from './components/PageSettingCom/PageSettingCom'
import TopImageCom from './components/TopImageCom/TopImageCom'
import GoodsRecommendCom from './components/GoodsRecommendCom/GoodsRecommendCom'
import FlipMove from 'react-flip-move'

const { Panel } = Collapse

const tabObj = {
  'mp-alipay': 1,
  'mp-weixin': 2,
  app: 3,
  h5: 4
}

function ActivityEditor() {
  const { message } = App.useApp()
  const [searchParams] = useSearchParams()

  const [activeKey, setActiveKey] = useState(['pageSetting', 'TopImage', 'coupon', 'goodsRecommend']) // 当前展开的面板

  const PageSettingComRef = useRef() // 页面设置组件
  const CouponComRef = useRef() // 优惠券组件
  const TopImageComRef = useRef() // 顶部图片组件
  const GoodsRecommendComRef = useRef() // 商品推荐组件

  const { pageSettingData, couponList, topImageData, goodsList, SavePageInfo, setCurrentTab, GetPageInfo } =
    useModel('ActivityEditor')

  // 组件列表
  const comList = [
    {
      key: 'pageSetting',
      label: '页面设置',
      children: () => {
        return <PageSettingCom ref={PageSettingComRef} />
      }
    },
    {
      key: 'TopImage',
      label: '顶部图片',
      children: () => {
        return <TopImageCom ref={TopImageComRef} />
      }
    },
    {
      key: 'coupon',
      label: '优惠券',
      children: () => {
        return <CouponCom ref={CouponComRef} />
      }
    },
    {
      key: 'goodsRecommend',
      label: '商品推荐',
      children: () => {
        return <GoodsRecommendCom ref={GoodsRecommendComRef} />
      }
    }
  ]

  // 提交事件
  const handleSubmit = async () => {
    // 页面数据
    const pageSettingValues = PageSettingComRef?.current && (await PageSettingComRef?.current?.handleFinish())

    // 顶部图片数据
    const topImageValues = TopImageComRef?.current && (await TopImageComRef?.current?.handleFinish())

    // 优惠券数据
    const couponValues = CouponComRef?.current && (await CouponComRef?.current?.handleFinish())

    // 商品推荐数据
    const goodsRecommendValues = GoodsRecommendComRef?.current && (await GoodsRecommendComRef?.current?.handleFinish())

    const values = {
      ...pageSettingValues,
      ...topImageValues,
      ...couponValues,
      ...goodsRecommendValues
    }

    if (!values.couponList.length && !values.goodsList.length) {
      message.error('优惠券和商品推荐列表至少有一个不能为空')
      return
    }

    // console.log('values----------', values)
    const res = await SavePageInfo({
      pageId: searchParams.get('pageId'),
      ...values
    })
    if (res) {
      message.success('发布成功')
    }
  }

  // 处理折叠面板切换
  const handleCollapseChange = key => {
    setActiveKey(key)
  }

  useEffect(() => {
    setCurrentTab(tabObj[searchParams.get('currentTab')])
    GetPageInfo({
      pageId: searchParams.get('pageId')
    })
  }, [])

  return (
    <>
      {couponList.length || goodsList.length || JSON.stringify(pageSettingData) !== '{}' ? (
        <div className='activity_editor'>
          <div className='header'>
            <div className='header_left'>
              <div className='header_left_title'>活动专题页</div>
              <div className='header_left_subtitle'>|</div>
              <div className='header_left_subtitle'>活动专题页面编辑器</div>
            </div>
            <div className='header_right'>
              <Popconfirm title='确认发布吗?' onConfirm={handleSubmit} okText='确认' cancelText='取消'>
                <Button type='primary'>立即发布</Button>
              </Popconfirm>
            </div>
          </div>

          <div className='wrapper'>
            <div></div>
            <div
              className='applet_view'
              style={{
                backgroundColor:
                  pageSettingData.backgroundColor === 'default' ? '#ff6787' : pageSettingData.backgroundColor
              }}
            >
              <div className='applet_view_status'></div>
              <div className='applet_view_title'>
                <div className='applet_view_title_text'>{pageSettingData.pageName}</div>
                <div className='applet_view_title_btn'></div>
              </div>

              <Tooltip title='页面设置' open={true} defaultOpen placement='left'>
                <div className='applet_view_content'>
                  <Tooltip title='顶部图片' open={true} defaultOpen placement='left'>
                    <header
                      className='applet_view_header'
                      style={{ backgroundImage: `url(${topImageData.topImage})` }}
                    ></header>
                  </Tooltip>

                  {couponList.length && (
                    <Tooltip title='优惠券' open={true} defaultOpen placement='left'>
                      <div className='coupon_list'>
                        <div className='coupon_box'>
                          <FlipMove duration={200} easing='ease-out'>
                            {couponList.map((item, index) => (
                              <div
                                key={item.id}
                                className={`coupon_item ${item.status === 0 ? 'coupon_item_disabled' : ''}`}
                              >
                                <div className='tag'>{item.tag}</div>
                                <div className='price_box'>
                                  <span>￥</span>
                                  {item.price}
                                </div>
                                <div className='coupon_item_info'>
                                  <div className='name'>{item.name}</div>
                                  <div className='content'>{item.content}</div>
                                  <div className='time'>{item.time}</div>
                                </div>
                                <div className='coupon_item_btn'>
                                  {item.status === 1 && <div>领取</div>}
                                  {item.status === 0 && <div>已抢完</div>}
                                </div>
                              </div>
                            ))}
                          </FlipMove>
                        </div>
                      </div>
                    </Tooltip>
                  )}

                  {goodsList.length > 0 && (
                    <Tooltip title='商品推荐' open={true} defaultOpen placement='left'>
                      <div className='goods_list'>
                        <div className='goods_box'>
                          <div className='goods_header' />
                          <div className='goods_content'>
                            <FlipMove duration={200} easing='ease-out'>
                              {goodsList.map((item, index) => (
                                <div key={item.id} className='goods_item'>
                                  <div className='goods_main_info'>
                                    {item.tag.map(item => {
                                      return (
                                        <div className='goods_tag' key={item.name}>
                                          {item.name}
                                        </div>
                                      )
                                    })}
                                    <img className='goods_img' src={item.img} alt='商品图片' />
                                  </div>
                                  <div className='goods_sub_info'>
                                    <div className='goods_name u-line-2'>{item.name}</div>

                                    {/*
                                    has_buy_meal 是否是购买套餐
                                    has_coupon 是否有优惠券
                                    has_rent_meal 是否有租赁套餐
                                  */}

                                    {/* 租赁 - 有券 */}
                                    {item.has_rent_meal && item.has_coupon ? (
                                      <>
                                        <div className='goods_price'>
                                          券后￥<span>{item.price}</span>/天起
                                        </div>
                                        <div className='goods_btn'>领券立租</div>
                                      </>
                                    ) : (
                                      // 租赁 - 无券  / 买卖 - 有券/无券
                                      <>
                                        <div className='goods_price'>
                                          ￥<span>{item.price}</span>/天起
                                        </div>
                                        <div className='goods_btn'>立即下单</div>
                                      </>
                                    )}
                                  </div>
                                </div>
                              ))}
                            </FlipMove>
                          </div>
                        </div>
                      </div>
                    </Tooltip>
                  )}
                </div>
              </Tooltip>
            </div>

            <div className='com_attr'>
              <Collapse activeKey={activeKey} bordered={false} onChange={handleCollapseChange}>
                {comList.map(item => {
                  return (
                    <Panel header={item.label} key={item.key}>
                      {item.children()}
                    </Panel>
                  )
                })}
              </Collapse>
            </div>
          </div>
        </div>
      ) : (
        <div className='activity_loading'>
          <Spin></Spin>
          <p>数据加载中...</p>
        </div>
      )}
    </>
  )
}

export default ActivityEditor
